import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Edit, Trash2, Play, Square } from "lucide-react";
import { ProxyRule } from "@shared/schema";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";

export function ProxyRulesTable() {
  const { toast } = useToast();
  
  const { data: proxyRules = [], isLoading } = useQuery({
    queryKey: ["/api/proxy-rules"],
  });

  const startProxyMutation = useMutation({
    mutationFn: (id: number) => apiRequest("POST", `/api/proxy-rules/${id}/start`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/proxy-rules"] });
      toast({ title: "代理已启动" });
    },
    onError: () => {
      toast({ title: "启动失败", variant: "destructive" });
    },
  });

  const stopProxyMutation = useMutation({
    mutationFn: (id: number) => apiRequest("POST", `/api/proxy-rules/${id}/stop`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/proxy-rules"] });
      toast({ title: "代理已停止" });
    },
    onError: () => {
      toast({ title: "停止失败", variant: "destructive" });
    },
  });

  const deleteProxyMutation = useMutation({
    mutationFn: (id: number) => apiRequest("DELETE", `/api/proxy-rules/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/proxy-rules"] });
      toast({ title: "代理规则已删除" });
    },
    onError: () => {
      toast({ title: "删除失败", variant: "destructive" });
    },
  });

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'running':
        return (
          <Badge className="bg-green-100 text-green-800 hover:bg-green-100">
            <div className="w-2 h-2 bg-green-500 rounded-full mr-2"></div>
            运行中
          </Badge>
        );
      case 'stopped':
        return (
          <Badge variant="secondary">
            <div className="w-2 h-2 bg-gray-500 rounded-full mr-2"></div>
            已停止
          </Badge>
        );
      case 'error':
        return (
          <Badge className="bg-red-100 text-red-800 hover:bg-red-100">
            <div className="w-2 h-2 bg-red-500 rounded-full mr-2"></div>
            错误
          </Badge>
        );
      default:
        return <Badge variant="outline">{status}</Badge>;
    }
  };

  const getTypeBadge = (type: string) => {
    const colors = {
      HTTP: "bg-blue-100 text-blue-800",
      HTTPS: "bg-green-100 text-green-800",
      TCP: "bg-purple-100 text-purple-800",
      UDP: "bg-orange-100 text-orange-800",
    };
    
    return (
      <Badge className={colors[type as keyof typeof colors] || "bg-gray-100 text-gray-800"}>
        {type}
      </Badge>
    );
  };

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>代理规则</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center h-32">
            <div className="text-slate-500">加载中...</div>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="text-lg font-semibold text-slate-800">代理规则</CardTitle>
            <p className="text-slate-600 text-sm">当前配置的反向代理规则</p>
          </div>
          <Button className="bg-primary hover:bg-blue-700">
            添加规则
          </Button>
        </div>
      </CardHeader>
      <CardContent className="p-0">
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow className="bg-slate-50">
                <TableHead className="font-medium text-slate-600">名称</TableHead>
                <TableHead className="font-medium text-slate-600">类型</TableHead>
                <TableHead className="font-medium text-slate-600">本地端口</TableHead>
                <TableHead className="font-medium text-slate-600">远程端口</TableHead>
                <TableHead className="font-medium text-slate-600">状态</TableHead>
                <TableHead className="font-medium text-slate-600">操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {proxyRules.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center py-8 text-slate-500">
                    暂无代理规则，请添加新规则
                  </TableCell>
                </TableRow>
              ) : (
                proxyRules.map((rule: ProxyRule) => (
                  <TableRow key={rule.id} className="hover:bg-slate-50">
                    <TableCell>
                      <div>
                        <div className="font-medium text-slate-800">{rule.name}</div>
                        {rule.description && (
                          <div className="text-sm text-slate-500">{rule.description}</div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>{getTypeBadge(rule.type)}</TableCell>
                    <TableCell className="text-slate-600">{rule.localPort}</TableCell>
                    <TableCell className="text-slate-600">{rule.remotePort}</TableCell>
                    <TableCell>{getStatusBadge(rule.status)}</TableCell>
                    <TableCell>
                      <div className="flex items-center space-x-2">
                        {rule.status === 'running' ? (
                          <Button 
                            size="sm" 
                            variant="ghost"
                            onClick={() => stopProxyMutation.mutate(rule.id)}
                            disabled={stopProxyMutation.isPending}
                          >
                            <Square className="h-4 w-4" />
                          </Button>
                        ) : (
                          <Button 
                            size="sm" 
                            variant="ghost"
                            onClick={() => startProxyMutation.mutate(rule.id)}
                            disabled={startProxyMutation.isPending}
                          >
                            <Play className="h-4 w-4" />
                          </Button>
                        )}
                        <Button size="sm" variant="ghost">
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button 
                          size="sm" 
                          variant="ghost"
                          onClick={() => deleteProxyMutation.mutate(rule.id)}
                          disabled={deleteProxyMutation.isPending}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
}
